import axios from 'axios'
import type { InternalAxiosRequestConfig, AxiosResponse, AxiosError } from 'axios'
import { message } from 'ant-design-vue'
import { useUserStore } from '@/stores'

// 定义后端响应的基础格式
export interface ApiResponse<T = any> {
  code: string
  data: T
  msg: string
}

// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_PREFIX,
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 添加token
    const { token } = useUserStore()
    if (token && config.headers) {
      config.headers.Authorization = token
    }
    return config
  },
  (error: AxiosError) => {
    console.error('请求错误:', error)
    // message.error('请求发送失败')
    return Promise.reject(error)
  },
)

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse<ApiResponse>) => {
    if (response.data.code != '1') {
      message.error(response.data.msg || '操作失败')
      return Promise.reject(new Error(response.data.msg || 'Error'))
    }
    return response.data.data
  },
  (error: AxiosError) => {
    console.error('响应错误:', error)
    // message.error(error.message || '网络错误')
    return Promise.reject(error)
  },
)

export default service
